package com.huibei.wateradmin.authority.service;

import com.huibei.wateradmin.authority.domain.Menu;
import com.huibei.wateradmin.authority.domain.Role;
import com.huibei.wateradmin.authority.message.ClientMenuTreeInfo;
import com.huibei.wateradmin.authority.message.ClientRoleInfo;
import com.huibei.wateradmin.authority.repository.MenuRepository;
import com.huibei.wateradmin.authority.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanglinlin on 2016/7/16.
 */
@Service
@Transactional
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private MenuRepository menuRepository;


    public Page<ClientRoleInfo> findByPage(PageRequest request) {
        return roleRepository.findAll(request).map(ClientRoleInfo::converToClient);
    }

    public List<ClientMenuTreeInfo> findMenusForTreeByRoleId(Long id) {
        //获取当前角色菜单
        Role role = roleRepository.findOne(id);
        List<Menu> roleMenus;
        if (role != null) {
            roleMenus = role.getMenus();
        } else {
            roleMenus = new ArrayList<>();
        }

        //获取所有菜单
        List<Menu> allMenus = menuRepository.findAll();
        List<ClientMenuTreeInfo> menuTreeInfos = new ArrayList<>();
        allMenus.forEach((Menu m) -> menuTreeInfos.add(ClientMenuTreeInfo.convertToClient(m,roleMenus)));

        return menuTreeInfos;
    }

    public void updateMenus(Long id, String description, String name, String menuIds){
        Role role = new Role(id,description,name);
        role = roleRepository.saveAndFlush(role); //这里必须改变role的引用
        role.emptyMenus();

        String[] ids = menuIds.split(",");
        for (String mid : ids) {
            //List menus 没有做级联 可以设置id方式映射
            Menu menu = new Menu();
            menu.setId(Long.parseLong(mid));
            role.addMenu(menu);
        }
    }


    public ClientRoleInfo findById(Long id) {
        Role one = roleRepository.findOne(id);
        return ClientRoleInfo.converToClient(one);
    }
}
